﻿using Leeder.Bluetooth;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Windows.Devices.Bluetooth;

namespace Bluetooth.SmartBracelet2
{
    public partial class Form1 : Form
    {
        string ip = "127.0.0.1";
        int port = 9996;
        Socket socket = null;
        Configs configs;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            smartBraceletUserControl1.SendDataEvent += SmartBraceletUserControl_SendDataEvent;
            smartBraceletUserControl2.SendDataEvent += SmartBraceletUserControl_SendDataEvent;
            smartBraceletUserControl3.SendDataEvent += SmartBraceletUserControl_SendDataEvent;
            smartBraceletUserControl4.SendDataEvent += SmartBraceletUserControl_SendDataEvent;
            smartBraceletUserControl5.SendDataEvent += SmartBraceletUserControl_SendDataEvent;
            smartBraceletUserControl6.SendDataEvent += SmartBraceletUserControl_SendDataEvent;
            smartBraceletUserControl7.SendDataEvent += SmartBraceletUserControl_SendDataEvent;
            string currentDirectory = Directory.GetCurrentDirectory();
            string filePath = Path.Combine(currentDirectory, "configs.json");
            // 从文件中读取JSON字符串
            string jsonFromFile = File.ReadAllText(filePath);
            // 将JSON字符串转换为ComboBox的数据源
            configs = JsonConvert.DeserializeObject<Configs>(jsonFromFile);
            foreach (SmartBraceletItem item in configs.SmartBraceletItems)
            {
                ListViewItem newItem = new ListViewItem(item.Name);
                newItem.SubItems.Add(item.Mac);
                listView1.Items.Add(newItem);
            }
            smartBraceletUserControl1.SetSmartBraceletItemList(configs.SmartBraceletItems);
            smartBraceletUserControl2.SetSmartBraceletItemList(configs.SmartBraceletItems);
            smartBraceletUserControl3.SetSmartBraceletItemList(configs.SmartBraceletItems);
            smartBraceletUserControl4.SetSmartBraceletItemList(configs.SmartBraceletItems);
            smartBraceletUserControl5.SetSmartBraceletItemList(configs.SmartBraceletItems);
            smartBraceletUserControl6.SetSmartBraceletItemList(configs.SmartBraceletItems);
            smartBraceletUserControl7.SetSmartBraceletItemList(configs.SmartBraceletItems);
            smartBraceletUserControl1.SelectWorker(configs.SmartBracelet1Worker);
            smartBraceletUserControl2.SelectWorker(configs.SmartBracelet2Worker);
            smartBraceletUserControl3.SelectWorker(configs.SmartBracelet3Worker);
            smartBraceletUserControl4.SelectWorker(configs.SmartBracelet4Worker);
            smartBraceletUserControl5.SelectWorker(configs.SmartBracelet5Worker);
            smartBraceletUserControl6.SelectWorker(configs.SmartBracelet6Worker);
            smartBraceletUserControl7.SelectWorker(configs.SmartBracelet7Worker);
            smartBraceletUserControl1.SelectSmartBracelet(configs.SmartBracelet1);
            smartBraceletUserControl2.SelectSmartBracelet(configs.SmartBracelet2);
            smartBraceletUserControl3.SelectSmartBracelet(configs.SmartBracelet3);
            smartBraceletUserControl4.SelectSmartBracelet(configs.SmartBracelet4);
            smartBraceletUserControl5.SelectSmartBracelet(configs.SmartBracelet5);
            smartBraceletUserControl6.SelectSmartBracelet(configs.SmartBracelet6);
            smartBraceletUserControl7.SelectSmartBracelet(configs.SmartBracelet7);
            smartBraceletUserControl1.Connect();
            smartBraceletUserControl2.Connect();
            smartBraceletUserControl3.Connect();
            smartBraceletUserControl4.Connect();
            smartBraceletUserControl5.Connect();
            smartBraceletUserControl6.Connect();
            smartBraceletUserControl7.Connect();
        }

        private void SmartBraceletUserControl_SendDataEvent(string groupName, string mac, string text)
        {
            Task.Run(() =>
            {
                SendData(groupName + "\t" + text);
            });
            try
            {
                statusStrip1.Invoke(new Action(() =>
                {
                    tslDateTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    tslWorker.Text = groupName;
                    tslMac.Text = mac;
                    tslText.Text = text;
                }));
            }
            catch { }
        }

        private void SendData(string iData)
        {
            try
            {
                Reconnect();
                byte[] array = Encoding.UTF8.GetBytes(iData);
                socket.Send(array, 0, array.Length, SocketFlags.None);
            }
            catch
            { }
        }

        /// <summary>
        /// 重连
        /// </summary>
        private void Reconnect()
        {
            try
            {
                if (socket != null && socket.Connected)
                    socket.Close();
            }
            catch { }
            try
            {
                socket = new Socket(SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
                socket.Connect(ip, port);
            }
            catch { }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Save();
            if (e.CloseReason == CloseReason.UserClosing)//当用户点击窗体右上角X按钮或(Alt + F4)时 发生          
            {
                e.Cancel = true;
                this.ShowInTaskbar = false;
                this.Hide();
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            AddForm addForm = new AddForm();
            addForm.SmartBraceletItems = configs.SmartBraceletItems;
            addForm.AddEvent += AddForm_AddEvent;
            addForm.Show();
        }

        private void AddForm_AddEvent(string mac, string name)
        {
            SmartBraceletItem newItem = new SmartBraceletItem { Name = name, Mac = mac };
            configs.SmartBraceletItems.Add(newItem);
            ListViewItem listViewItem = new ListViewItem(newItem.Name);
            listViewItem.SubItems.Add(newItem.Mac);
            listView1.Items.Add(listViewItem);
            Save();
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                int selectedIndex = listView1.SelectedItems[0].Index;
                configs.SmartBraceletItems.RemoveAt(selectedIndex);
                listView1.Items.RemoveAt(selectedIndex);
                Save();
            }
        }

        protected void Save()
        {
            configs.SmartBracelet1Worker = smartBraceletUserControl1.SelectedWorker;
            configs.SmartBracelet2Worker = smartBraceletUserControl2.SelectedWorker;
            configs.SmartBracelet3Worker = smartBraceletUserControl3.SelectedWorker;
            configs.SmartBracelet4Worker = smartBraceletUserControl4.SelectedWorker;
            configs.SmartBracelet5Worker = smartBraceletUserControl5.SelectedWorker;
            configs.SmartBracelet6Worker = smartBraceletUserControl6.SelectedWorker;
            configs.SmartBracelet7Worker = smartBraceletUserControl7.SelectedWorker;
            configs.SmartBracelet1 = smartBraceletUserControl1.SelectedSmartBracelet;
            configs.SmartBracelet2 = smartBraceletUserControl2.SelectedSmartBracelet;
            configs.SmartBracelet3 = smartBraceletUserControl3.SelectedSmartBracelet;
            configs.SmartBracelet4 = smartBraceletUserControl4.SelectedSmartBracelet;
            configs.SmartBracelet5 = smartBraceletUserControl5.SelectedSmartBracelet;
            configs.SmartBracelet6 = smartBraceletUserControl6.SelectedSmartBracelet;
            configs.SmartBracelet7 = smartBraceletUserControl7.SelectedSmartBracelet;
            string currentDirectory = Directory.GetCurrentDirectory();
            string filePath = Path.Combine(currentDirectory, "configs.json");
            string json = JsonConvert.SerializeObject(configs);
            // 保存JSON字符串到文件
            File.WriteAllText(filePath, json);
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip1.Show();
            }

            if (e.Button == MouseButtons.Left)
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}
